<?php

/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2018/11/29
 * Time: 4:38 PM
 */
namespace app\shop\traits;

trait Goods
{
    public function getGoodsImagesAttr($goodsImages)
    {
        if (is_array($goodsImages)) return $goodsImages;
        if (empty($goodsImages)) return [];

        return array_map(function($goodsImage) {
            return GOODS_IMAGE_URL . $goodsImage;
        }, explode(',', $goodsImages));
    }

    public function getGoodsSpecsAttr($goodsSpecs)
    {
        if (!is_string($goodsSpecs)) return $goodsSpecs;
        return json_decode($goodsSpecs, true);
    }

    public function getPriceAttr($price)
    {
        return floatval($price);
    }

    /**
     * 规格
     */
    public function specs()
    {
        /* @var $this \think\Model */
        return $this->hasMany('GoodsSpec', 'sku_id', 'sku_id')
            ->field('spec_id, spec_name, show_type')
            ->where('is_hidden', 0)
            ->order('sort_order', 'desc');
    }

    /**
     * 单位
     */
    public function units()
    {
        /* @var $this \think\Model */
        return $this->belongsToMany('Unit', 'sh_goods_sku_unit', 'unit_id', 'sku_id')
            ->where('is_delete', 0)
            ->order('sort_order', 'desc');
    }

    /**
     * 品牌
     */
    public function brand()
    {
        /* @var $this \think\Model */
        return $this->belongsTo('Brand', 'brand_id', 'brand_id')
            ->field('brand_id, brand_name, brand_logo');
    }

    /**
     * 分类
     */
    public function category()
    {
        /* @var $this \think\Model */
        return $this->belongsTo('Category', 'cate_id', 'cate_id')
            ->field('cate_id, cate_name');
    }

}